package com.ruoyi.door.utils.baofu;


import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.easy.query.api.proxy.client.EasyEntityQuery;
import com.ruoyi.common.core.domain.entity.MemberCard;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.door.controller.app.baofu.vo.SinglePayReqVO;
import com.ruoyi.door.domain.DoorOrder;
import com.ruoyi.door.service.DoorMemberCardService;
import com.ruoyi.door.utils.baofu.entity.ContentEntity;
import com.ruoyi.door.utils.baofu.entity.RefundPostEntity;
import com.ruoyi.door.utils.baofu.http.HttpUtil;
import com.ruoyi.door.utils.baofu.rsa.RsaCodingUtil;
import com.ruoyi.door.utils.baofu.rsa.SignatureUtils;
import com.ruoyi.door.utils.baofu.util.FormatUtil;
import com.ruoyi.door.utils.baofu.util.SecurityUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

@Service
@Slf4j
public class BaoFuXieYiService {



    @Autowired
    private ResourceLoader resourceLoader;
    @Autowired
    private EasyEntityQuery easyEntityQuery;

    public String getResourcePath(String resourcePath) throws IOException {
        Resource resource = resourceLoader.getResource("classpath:" + resourcePath);
        File file = resource.getFile();
        return file.getAbsolutePath();
    }
    public Map<String, String> unSign(String protocolNo){
        try {

            String ProtocolNo = protocolNo;//"1202411111040078480001616292";//签约协议号（确认绑卡返回）
            String MemberId = BaoFuConstants.MEMBER_ID;//商户号
            String TerminalId = BaoFuConstants.TERMINAL_ID;//终端号

            String  pfxpath ="D:\\CER_EN_DECODE\\NTestNewKey\\NewTestKey\\BAOFU20240612_pri.pfx";//商户私钥
            String  cerpath = "D:\\CER_EN_DECODE\\NTestNewKey\\NewTestKey\\BAOFUP20240612_pub.cer";//宝付公钥
            String  pfxpwd = BaoFuConstants.PASS_WORD;//私钥密码
            pfxpath = BaofuUtil.getPath(BaoFuConstants.PFX_PATH);
            cerpath = BaofuUtil.getPath(BaoFuConstants.CER_PATH);

            String send_time=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());//报文发送日期时间
            String AesKey = FormatUtil.CreateAeskey();//商户自定义(可随机生成  AES key长度为=16位)
            String dgtl_envlp = "01|"+AesKey;//使用接收方的公钥加密后的对称密钥，并做Base64转码，明文01|对称密钥，01代表AES[密码商户自定义]
            log.info("密码dgtl_envlp："+dgtl_envlp);
            dgtl_envlp = RsaCodingUtil.encryptByPubCerFile(SecurityUtil.Base64Encode(dgtl_envlp), cerpath);//公钥加密

            log.info("签约协议号："+ProtocolNo);
            ProtocolNo = SecurityUtil.AesEncrypt(SecurityUtil.Base64Encode(ProtocolNo), AesKey);//先BASE64后进行AES加密
            log.info("签约协议号AES结果:"+ProtocolNo);

            Map<String,String> DateArry = new TreeMap<String,String>();
            DateArry.put("send_time", send_time);
            DateArry.put("msg_id", "TISN"+FormatUtil.CreateAeskey(28));//报文流水号
            DateArry.put("version", "4.0.0.0");
            DateArry.put("terminal_id", TerminalId);
            DateArry.put("txn_type", "04");//交易类型
            DateArry.put("member_id", MemberId);
            DateArry.put("dgtl_envlp", dgtl_envlp);
            DateArry.put("user_id", "");//用户在商户平台唯一ID (和绑卡时要一致)
            DateArry.put("protocol_no", ProtocolNo);//签约协议号（密文）

            String SignVStr = FormatUtil.coverMap2String(DateArry);
            log.info("SHA-1摘要字串："+SignVStr);
            String signature = SecurityUtil.sha1X16(SignVStr, "UTF-8");//签名
            log.info("SHA-1摘要结果："+signature);
            String Sign = SignatureUtils.encryptByRSA(signature, pfxpath, pfxpwd);
            log.info("RSA签名结果："+Sign);
            DateArry.put("signature", Sign);//签名域

            String PostString  = HttpUtil.RequestForm(BaoFuConstants.BAOFU_XIEYI_URL+"/cutpayment/protocol/backTransRequest", DateArry);
            log.info("请求返回:"+PostString);

            Map<String, String> ReturnData = FormatUtil.getParm(PostString);

            if(!ReturnData.containsKey("signature")){
                throw new Exception("缺少验签参数！");
            }

            String RSign=ReturnData.get("signature");
            log.info("返回的验签值："+RSign);
            ReturnData.remove("signature");//需要删除签名字段
            String RSignVStr = FormatUtil.coverMap2String(ReturnData);
            log.info("返回SHA-1摘要字串："+RSignVStr);
            String RSignature = SecurityUtil.sha1X16(RSignVStr, "UTF-8");//签名
            log.info("返回SHA-1摘要结果："+RSignature);

            if(SignatureUtils.verifySignature(cerpath,RSignature,RSign)){
                log.info("Yes");//验签成功
            }
            if(!ReturnData.containsKey("resp_code")){
                throw new Exception("缺少resp_code参数！");
            }
            if(ReturnData.get("resp_code").toString().equals("S")){
                log.info("解绑成功！");
                easyEntityQuery.deletable(MemberCard.class).allowDeleteStatement(true)
                        .disableLogicDelete()
                        .where(m -> m.protocolNo().eq(protocolNo)).executeRows();

            }else if(ReturnData.get("resp_code").toString().equals("F")){
                log.info("解绑失败！");
            }
            return ReturnData;

        }catch (Exception ex){
            ex.printStackTrace();
            throw new ServiceException(ex.getMessage());

        }
    }
    /**
     * @param cardIndo "6222021001015343573|王勇|310115200501018559|18616092709||";//账户信息[银行卡号|持卡人姓名|证件号|手机号|银行卡安全码|银行卡有效期
     * @param cardType 卡类型  101	借记卡，102 信用卡
     */
    public Map<String, String> readySign(String cardIndo, String cardType, String userId) {
        try {
            String send_time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());//报文发送日期时间
            String MemberId = BaoFuConstants.MEMBER_ID;//商户号
            String TerminalId = BaoFuConstants.TERMINAL_ID;//终端号
            String Cardinfo = cardIndo;


            String pfxpath = "./baofu/BAOFU20240612_pri.pfx";//商户私钥
            String cerpath = "./baofu/BAOFUP20240612_pub.cer";//宝付公钥
            String pfxpwd = BaoFuConstants.PASS_WORD;//私钥密码
            pfxpath = BaofuUtil.getPath(BaoFuConstants.PFX_PATH);
            cerpath = BaofuUtil.getPath(BaoFuConstants.CER_PATH);

            String AesKey = FormatUtil.CreateAeskey();//商户自定义（可随机生成  商户自定义(AES key长度为=16位)）
            String dgtl_envlp = "01|" + AesKey;//使用接收方的公钥加密后的对称密钥，并做Base64转码，明文01|对称密钥，01代表AES[密码商户自定义]
            log.info("密码dgtl_envlp：" + dgtl_envlp);
            dgtl_envlp = RsaCodingUtil.encryptByPubCerFile(SecurityUtil.Base64Encode(dgtl_envlp), cerpath);//公钥加密

            Cardinfo = SecurityUtil.AesEncrypt(SecurityUtil.Base64Encode(Cardinfo), AesKey);//先BASE64后进行AES加密
            log.info("AES结果:" + Cardinfo);

            Map<String, String> DateArry = new TreeMap<String, String>();
            DateArry.put("send_time", send_time);
            DateArry.put("msg_id", "TISN" + FormatUtil.CreateAeskey(28));//报文流水号
            DateArry.put("version", "4.0.0.0");
            DateArry.put("terminal_id", TerminalId);
            DateArry.put("txn_type", "01");//交易类型
            DateArry.put("member_id", MemberId);
            DateArry.put("dgtl_envlp", dgtl_envlp);
            DateArry.put("user_id", userId);
            DateArry.put("card_type", cardType);//卡类型  101	借记卡，102 信用卡
            DateArry.put("id_card_type", "01");//证件类型
            DateArry.put("acc_info", Cardinfo);

            String SignVStr = FormatUtil.coverMap2String(DateArry);
            log.info("SHA-1摘要字串：" + SignVStr);
            String signature = SecurityUtil.sha1X16(SignVStr, "UTF-8");//签名
            log.info("SHA-1摘要结果：" + signature);

            String Sign = SignatureUtils.encryptByRSA(signature, pfxpath, pfxpwd);
            log.info("RSA签名结果：" + Sign);
            DateArry.put("signature", Sign);//签名域

            String PostString = HttpUtil.RequestForm(BaoFuConstants.BAOFU_XIEYI_URL + "/cutpayment/protocol/backTransRequest", DateArry);
            log.info("请求返回:" + PostString);

            Map<String, String> ReturnData = FormatUtil.getParm(PostString);
            if (!ReturnData.containsKey("signature")) {
                throw new Exception("缺少验签参数！");
            }

            String RSign = ReturnData.get("signature");
            log.info("返回的验签值：" + RSign);
            ReturnData.remove("signature");//需要删除签名字段
            String RSignVStr = FormatUtil.coverMap2String(ReturnData);
            log.info("返回SHA-1摘要字串：" + RSignVStr);
            String RSignature = SecurityUtil.sha1X16(RSignVStr, "UTF-8");//签名
            log.info("返回SHA-1摘要结果：" + RSignature);

            if (SignatureUtils.verifySignature(cerpath, RSignature, RSign)) {
                log.info("Yes");//验签成功
            }

            if (!ReturnData.containsKey("resp_code")) {
                throw new ServiceException("缺少resp_code参数！");
            }
            if (ReturnData.get("resp_code").toString().equals("S")) {
                if (!ReturnData.containsKey("dgtl_envlp")) {
                    throw new ServiceException("缺少dgtl_envlp参数！");
                }
                String RDgtlEnvlp = SecurityUtil.Base64Decode(RsaCodingUtil.decryptByPriPfxFile(ReturnData.get("dgtl_envlp"), pfxpath, pfxpwd));
                log.info("返回数字信封：" + RDgtlEnvlp);
                String RAesKey = FormatUtil.getAesKey(RDgtlEnvlp);//获取返回的AESkey
                log.info("返回的AESkey:" + RAesKey);
                log.info("唯一码:" + SecurityUtil.Base64Decode(SecurityUtil.AesDecrypt(ReturnData.get("unique_code"), RAesKey)));
                ReturnData.put("unique_code2", SecurityUtil.Base64Decode(SecurityUtil.AesDecrypt(ReturnData.get("unique_code"), RAesKey)));
            }
            return ReturnData;
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new ServiceException(ex.getMessage());
        }
    }


    public Map<String, String> confirmSign(String uniqueCode, String ssmcode) {
        Map<String, Object> map = new HashMap<>();
        try {
            String send_time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());//报文发送日期时间
            String MemberId = BaoFuConstants.MEMBER_ID;//商户号
            String TerminalId = BaoFuConstants.TERMINAL_ID;//终端号

            String pfxpath = "D:\\CER_EN_DECODE\\NTestNewKey\\NewTestKey\\BAOFU20240612_pri.pfx";//商户私钥
            String cerpath = "D:\\CER_EN_DECODE\\NTestNewKey\\NewTestKey\\BAOFUP20240612_pub.cer";//宝付公钥
            String pfxpwd = BaoFuConstants.PASS_WORD;//私钥密码
            pfxpath = BaofuUtil.getPath(BaoFuConstants.PFX_PATH);
            cerpath = BaofuUtil.getPath(BaoFuConstants.CER_PATH);

            String SMSStr = ssmcode;//"411425";//短信验证码，测试环境随机6位数;生产环境验证码预绑卡成功后发到用户手机。确认绑卡时回传。

            String AesKey = FormatUtil.CreateAeskey();//商户自定义（可随机生成  商户自定义(AES key长度为=16位)）
            String dgtl_envlp = "01|" + AesKey;//使用接收方的公钥加密后的对称密钥，并做Base64转码，明文01|对称密钥，01代表AES[密码商户自定义]

            log.info("密码dgtl_envlp：" + dgtl_envlp);
            dgtl_envlp = RsaCodingUtil.encryptByPubCerFile(SecurityUtil.Base64Encode(dgtl_envlp), cerpath);//公钥加密
            String UniqueCode = uniqueCode + "|" + SMSStr;//预签约唯一码(预绑卡返回的值)[格式：预签约唯一码|短信验证码]
            log.info("预签约唯一码：" + UniqueCode);
            UniqueCode = SecurityUtil.AesEncrypt(SecurityUtil.Base64Encode(UniqueCode), AesKey);//先BASE64后进行AES加密
            log.info("AES结果:" + UniqueCode);

            Map<String, String> DateArry = new TreeMap<String, String>();
            DateArry.put("send_time", send_time);
            DateArry.put("msg_id", "TISN" + FormatUtil.CreateAeskey(28));//报文流水号
            DateArry.put("version", "4.0.0.0");
            DateArry.put("terminal_id", TerminalId);
            DateArry.put("txn_type", "02");//交易类型
            DateArry.put("member_id", MemberId);
            DateArry.put("dgtl_envlp", dgtl_envlp);
            DateArry.put("unique_code", UniqueCode);//预签约唯一码

            String SignVStr = FormatUtil.coverMap2String(DateArry);
            log.info("SHA-1摘要字串：" + SignVStr);
            String signature = SecurityUtil.sha1X16(SignVStr, "UTF-8");//签名
            log.info("SHA-1摘要结果：" + signature);
            String Sign = SignatureUtils.encryptByRSA(signature, pfxpath, pfxpwd);
            log.info("RSA签名结果：" + Sign);
            DateArry.put("signature", Sign);//签名域
            String PostString = HttpUtil.RequestForm(BaoFuConstants.BAOFU_XIEYI_URL + "/cutpayment/protocol/backTransRequest", DateArry);
            log.info("请求返回:" + PostString);

            Map<String, String> ReturnData = FormatUtil.getParm(PostString);

            if (!ReturnData.containsKey("signature")) {
                throw new Exception("缺少验签参数！");
            }

            String RSign = ReturnData.get("signature");
            log.info("返回的验签值：" + RSign);
            ReturnData.remove("signature");//需要删除签名字段
            String RSignVStr = FormatUtil.coverMap2String(ReturnData);
            log.info("返回SHA-1摘要字串：" + RSignVStr);
            String RSignature = SecurityUtil.sha1X16(RSignVStr, "UTF-8");//签名
            log.info("返回SHA-1摘要结果：" + RSignature);

            if (SignatureUtils.verifySignature(cerpath, RSignature, RSign)) {
                log.info("Yes");//验签成功
            }
            if (!ReturnData.containsKey("resp_code")) {
                throw new Exception("缺少resp_code参数！");
            }
            if (ReturnData.get("resp_code").toString().equals("S")) {
                if (!ReturnData.containsKey("dgtl_envlp")) {
                    throw new Exception("缺少dgtl_envlp参数！");
                }
                String RDgtlEnvlp = SecurityUtil.Base64Decode(RsaCodingUtil.decryptByPriPfxFile(ReturnData.get("dgtl_envlp"), pfxpath, pfxpwd));
                log.info("返回数字信封：" + RDgtlEnvlp);
                String RAesKey = FormatUtil.getAesKey(RDgtlEnvlp);//获取返回的AESkey
                log.info("返回的AESkey:" + RAesKey);
                log.info("签约协议号:" + SecurityUtil.Base64Decode(SecurityUtil.AesDecrypt(ReturnData.get("protocol_no"), RAesKey)));
                ReturnData.put("protocol_no2", SecurityUtil.Base64Decode(SecurityUtil.AesDecrypt(ReturnData.get("protocol_no"), RAesKey)));

            } else if (ReturnData.get("resp_code").toString().equals("I")) {
                log.info("处理中！");
            } else if (ReturnData.get("resp_code").toString().equals("F")) {
                log.info("失败！");
            } else {
                throw new Exception("反回异常！");//异常不得做为订单状态。
            }

            return ReturnData;
        } catch (Exception ex) {
            ex.printStackTrace();
            map.put("code", 500);
            throw new ServiceException(ex.getMessage());
        }
    }

    public Map<String, String> singlePay(SinglePayReqVO reqVo
    ) {
        try {
            String send_time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());//报文发送日期时间
            //send_time="2038-12-23 10:00:00";
            String ProtocolNo = reqVo.getProtocolNo();//"1202411111040078480001616292";//签约协议号（确认绑卡返回）

            String MemberId = BaoFuConstants.MEMBER_ID;//商户号
            String TerminalId = BaoFuConstants.TERMINAL_ID;//终端号

            String pfxpath = "D:\\CER_EN_DECODE\\NTestNewKey\\NewTestKey\\BAOFU20240612_pri.pfx";//商户私钥
            String cerpath = "D:\\CER_EN_DECODE\\NTestNewKey\\NewTestKey\\BAOFUP20240612_pub.cer";//宝付公钥
            String pfxpwd = BaoFuConstants.PASS_WORD;//私钥密码
            pfxpath = BaofuUtil.getPath(BaoFuConstants.PFX_PATH);
            cerpath = BaofuUtil.getPath(BaoFuConstants.CER_PATH);

            String ReturnUrl = BaoFuConstants.XIEYI_PAY_CALLBACK;//异步通知接收地址
            String TransId = reqVo.getOrderNo();//"TID" + FormatUtil.CreateAeskey(20);//商户订单号

            log.info("订单号：" + TransId);

            String AesKey = FormatUtil.CreateAeskey();//商户自定义(可随机生成  AES key长度为=16位)
            String dgtl_envlp = "01|" + AesKey;//+AesKey;//使用接收方的公钥加密后的对称密钥，并做Base64转码，明文01|对称密钥，01代表AES[密码商户自定义]
            log.info("密码dgtl_envlp：" + dgtl_envlp);
            dgtl_envlp = RsaCodingUtil.encryptByPubCerFile(SecurityUtil.Base64Encode(dgtl_envlp), cerpath);//公钥加密
            log.info("RSA公钥加密结果" + dgtl_envlp);


            ProtocolNo = SecurityUtil.AesEncrypt(SecurityUtil.Base64Encode(ProtocolNo), AesKey);//先BASE64后进行AES加密
            log.info("签约协议号AES结果:" + ProtocolNo);

            String CardInfo = "";//信用卡：信用卡有效期|安全码,借记卡：传空

            //暂不支持信用卡
            CardInfo = SecurityUtil.AesEncrypt(SecurityUtil.Base64Encode(CardInfo), AesKey);//先BASE64后进行AES加密


            Map<String, String> DateArry = new TreeMap<String, String>();
            DateArry.put("send_time", send_time);
            DateArry.put("msg_id", "TISN" + System.currentTimeMillis());//报文流水号
            DateArry.put("version", "4.0.0.0");
            DateArry.put("terminal_id", TerminalId);
            DateArry.put("txn_type", "08");//交易类型(参看：文档中《交易类型枚举》)
            DateArry.put("member_id", MemberId);
            DateArry.put("trans_id", TransId);
            DateArry.put("dgtl_envlp", dgtl_envlp);
            DateArry.put("user_id", reqVo.getUserId());//用户在商户平台唯一ID (和绑卡时要一致)
            DateArry.put("protocol_no", ProtocolNo);//签约协议号（密文）
            DateArry.put("txn_amt", reqVo.getAmount());//交易金额 [单位：分  例：1元则提交100]，此处注意数据类型的转转，建议使用BigDecimal类弄进行转换为字串
            DateArry.put("card_info", CardInfo);//卡信息

//		DateArry.put("fee_member_id", "");//手续费商户

            Map<String, String> RiskItem = new HashMap<String, String>();
            /**--------风控基础参数-------------**/
            /**
             * 说明风控参数必须，按商户开通行业、真实交易信息传，不可传固定值。
             */
            //01电商;02互金消金;3
            //https://docs.baofu.com/docs/qyzf/qyzf-1gc73p3cgir9f
            RiskItem.put("goodsCategory", "02");//商品类目 详见附录《商品类目》
            RiskItem.put("userLoginId", reqVo.getUserName());//用户在商户系统中的登陆名（手机号、邮箱等标识）
            RiskItem.put("userEmail", reqVo.getEmail());
            RiskItem.put("userMobile", reqVo.getPhone());//用户手机号
            RiskItem.put("registerUserName", reqVo.getNickName());//用户在商户系统中注册使用的名字
            RiskItem.put("identifyState", reqVo.getIdentifyState());//用户在平台是否已实名，1：是 ；0：不是
            RiskItem.put("userIdNo", reqVo.getIdCard());//用户身份证号
            RiskItem.put("registerTime", DateUtil.format(reqVo.getRegisterTime(), DatePattern.PURE_DATETIME_PATTERN));//格式为：YYYYMMDDHHMMSS
            RiskItem.put("registerIp", reqVo.getRegisterIp());//用户在商户端注册时留存的IP
            RiskItem.put("chName", reqVo.getChName());//持卡人姓名
            RiskItem.put("chIdNo", reqVo.getChIdNo());//持卡人身份证号
            RiskItem.put("chCardNo", reqVo.getChCardNo());//持卡人银行卡号
            RiskItem.put("chMobile", reqVo.getChMobile());//持卡人手机
            RiskItem.put("chPayIp", reqVo.getPayIp());//持卡人支付IP
            RiskItem.put("deviceOrderNo", "");//加载设备指纹中的订单号


            /**--------行业参数  (以下为游戏行业风控参，请参看接口文档附录风控参数)-------------**/
            RiskItem.put("tradeType", "1");//充值游戏名称
//            RiskItem.put("customerType", "15821798636");//游戏账户ID
//            RiskItem.put("rechargeType", "0");//充值类型 (0:为本账户充值或支付、1:为他人账户充值或支付； 默认为 0)
//            RiskItem.put("gameProdType", "02");//01：点券类 、 02：金币类 、 03：装备道具类 、 04：其他
//            RiskItem.put("gameAcctId", "");//被充值游戏账户ID,若充值类型为1 则填写
//            RiskItem.put("gameLoginTime", "20");//游戏登录次数，累计最近一个月
//            RiskItem.put("gameOnlineTime", "100");//游戏在线时长，累计最近一个月

            DateArry.put("risk_item", JSONObject.toJSONString(RiskItem).toString());//放入风控参数
            DateArry.put("return_url", ReturnUrl);//最多填写三个地址,不同地址用间使用‘|’分隔

            String SignVStr = FormatUtil.coverMap2String(DateArry);
            log.info("SHA-1摘要字串：" + SignVStr);
            String signature = SecurityUtil.sha1X16(SignVStr, "UTF-8");//签名
            log.info("SHA-1摘要结果：" + signature);
            String Sign = SignatureUtils.encryptByRSA(signature, pfxpath, pfxpwd);
            log.info("RSA签名结果：" + Sign);
            DateArry.put("signature", Sign);//签名域

            String PostString = HttpUtil.RequestForm(BaoFuConstants.BAOFU_XIEYI_URL + "/cutpayment/protocol/backTransRequest", DateArry);
            log.info("请求返回:" + PostString);

            Map<String, String> ReturnData = FormatUtil.getParm(PostString);

            if (!ReturnData.containsKey("signature")) {
                throw new Exception("缺少验签参数！");
            }
            String RSign = ReturnData.get("signature");
            log.info("返回的验签值：" + RSign);
            ReturnData.remove("signature");//需要删除签名字段
            String RSignVStr = FormatUtil.coverMap2String(ReturnData);
            log.info("返回SHA-1摘要字串：" + RSignVStr);
            String RSignature = SecurityUtil.sha1X16(RSignVStr, "UTF-8");//签名
            log.info("返回SHA-1摘要结果：" + RSignature);

            if (SignatureUtils.verifySignature(cerpath, RSignature, RSign)) {
                log.info("验签：Yes");//验签成功

                if (!ReturnData.containsKey("resp_code")) {
                    throw new Exception("缺少resp_code参数！");
                }
                if (ReturnData.get("resp_code").toString().equals("S")) {
                    log.info("支付成功！");
                } else if (ReturnData.get("resp_code").toString().equals("I")) {
                    log.info("交易处理中！");
                } else if (ReturnData.get("resp_code").toString().equals("F")) {
                    log.info("交易失败！");
                } else {
                    throw new Exception("反回异常！");//异常不得做为订单状态。
                }
            } else {
                log.info("验签：NO");
            }
            return ReturnData;
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new ServiceException(ex.getMessage());
        }
    }

    public JSONObject refund(DoorOrder orderInfo){
        try {
            ContentEntity recv=new ContentEntity();
            recv.setRefund_amt(String.valueOf(orderInfo.getTotalPrice().multiply(BigDecimal.valueOf(100)).intValue()));
            recv.setRefund_reason("不想要了");
            recv.setRefund_type("8");
            recv.setTrans_id(orderInfo.getOrderNo());
            log.info("退款申请入参："+ JSON.toJSONString(recv));
            String TxnSubType="09";//退款申请
            String trade_date=new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());//退款发起时间
            recv.setMember_id(BaoFuConstants.MEMBER_ID);
            recv.setTerminal_id(BaoFuConstants.TERMINAL_ID);
            recv.setNotice_url(BaoFuConstants.XIEYI_REFUND_CALLBACK);
            recv.setTxn_sub_type(TxnSubType);//退款申请
            recv.setRefund_order_no(orderInfo.getRefundNo());
            recv.setTrans_serial_no("TSN"+FormatUtil.CreateAeskey(16));
            recv.setRefund_time(trade_date);
            String JsonData = JSON.toJSONString(recv);
            log.info("DataContent报文："+JsonData);
            String pfxpath =  BaofuUtil.getPath(BaoFuConstants.PFX_PATH);;
            log.info("私钥证书路径："+pfxpath);

            String base64str = SecurityUtil.Base64Encode(JsonData);//base64转码
            String enContent = RsaCodingUtil.encryptByPriPfxFile(base64str, pfxpath,BaoFuConstants.PASS_WORD);

            RefundPostEntity PostHead = new RefundPostEntity();
            PostHead.setMember_id(BaoFuConstants.MEMBER_ID);
            PostHead.setTerminal_id(BaoFuConstants.TERMINAL_ID);
            PostHead.setData_type("json");//示列只用JSON
            PostHead.setTxn_sub_type(TxnSubType);
            PostHead.setVersion("4.0.0.0");//版本号以对应接口文档为准
            PostHead.setData_content(enContent);
            PostHead.setTxn_type("331");//固定值
            String Result = HttpUtil.RequestForm(BaoFuConstants.BAOFU_XIEYI_URL +"/cutpayment/api/backTransRequest",PostHead);
            if(StringUtils.isBlank(Result)) throw new Exception("请求响应为空");
            log.info("请求响应："+Result);
            String cerpath = BaofuUtil.getPath(BaoFuConstants.CER_PATH);;
            log.info("公钥证书路径："+cerpath);

            try {
                String DeCodeResult = RsaCodingUtil.decryptByPubCerFile(Result,cerpath);
                String Base64Dec = SecurityUtil.Base64Decode(DeCodeResult);
                Result = Base64Dec;
                log.info("解密结果："+Result);
            }catch (Exception ex){
                log.error("返回解密异常",ex);
                throw new Exception("返回数据解密异常");
            }
            return JSONObject.parseObject(Result);
        }catch (Exception ex){
            log.error("",ex);
            throw new ServiceException("本地异常，请检查参数["+ex.getMessage()+"]");
        }
    }
}
